package HashTablePackage;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lzm
 * @version 1.0
 */
public class twoSum_ {
@Test
public void twoSumTest(){
  int[] nums = new int[]{2,7,11,15};
  int target = 9;

}
  /*public static int[] twoSum(int[] nums, int target){
    *//*定义结果数组*//*
    int[] result = new int[2];
    *//*定义Map[key(表示nums中的值) , value(表示下标)]*//*
    Map<Integer,Integer> hashTa = new HashMap<>();
    for (int i = 0 ; i < nums.length ; i++){
      *//*定义新target*//*
      int newTarget = target - nums[i];
      *//*判断newTarget是否在map中出现过*//*
      if(hashTa.containsKey(newTarget)){
        result[0] = i;
        result[1] = hashTa.get(newTarget);
      }
      else{
        hashTa.put(nums[i],i);
      }
    }
    return result;
  }*/


  public int[] twoSum(int[] nums, int target) {
    Map<Integer,Integer> map = new HashMap<>();
    int[] result = new int[2];
    for (int i = 0; i < nums.length; i++) {
      int newTarget = target - nums[i];
      if (map.containsKey(newTarget)){
        result[0] = i;
        result[1] = map.get(newTarget);
      }
      else{
        map.put(nums[i],i);
      }
    }
    return result;
  }
}
